/*
* ============================================================================
* 功能描述 ：GPIO模拟I2C功能温湿度
* 作者       ：ggls
* 创建日期 ：2024.04.24
* ----------------------------------------------------------------------------
* 更新历史 ：
*	日期 　　- 修改者   : 更新内容描述
*
* ============================================================================
*/

#include "main.h"


//模拟IIC初始化
void I2CInit()
{
    SCL_out;
    SDA_out;
}


void I2C_delay()
{
   Delayus(20);
 
}

void I2CStart()
{
    SDA_out;
	Delayus(5);
    SCL_H;
    SDA_H;
	Delayus(10);
    SDA_L;
	Delayus(10);

    SCL_L;
}

void I2CStop()
{
    SDA_out;
	Delayus(5);
    SCL_L;
    SDA_L;
	Delayus(10);
    SCL_H;
	Delayus(10);
    SDA_H;
	Delayus(10);
}

unsigned char I2CWrite(unsigned char I2Cdata)
{
     unsigned char mask;

     SDA_out;
	 Delayus(5);
     for (mask = 0x80; mask != 0; mask >>= 1)
     {
         if (mask & I2Cdata)
             SDA_H;
         else
             SDA_L;
		 Delayus(10);
         SCL_H;
		 Delayus(10);
         SCL_L;
     }
     SDA_H;
     SDA_in;
	 Delayus(10);
     SCL_H;
	 Delayus(10);
     if(P16)
     {
         SCL_L;
         return 0;
     }
     else
     {
         SCL_L;
         return 1;
     }
}
unsigned char I2CAddress(unsigned char address)
{
    unsigned char ack = 0;

     I2CStart();
     ack = I2CWrite(address);
     I2CStop();

     return ack;
}
unsigned char I2CReadACK()
{
     unsigned char mask;
     unsigned char I2Cdata;

     SDA_H;
     SDA_in;

     for(mask = 0x80;mask != 0; mask >>= 1)
     {
		 Delayus(10);
         SCL_H;
          if(P16 == 0)
              I2Cdata &= ~mask;
          else
              I2Cdata |= mask;
		  Delayus(10);
          SCL_L;
     }
     SDA_out;
	 Delayus(5);
     SDA_L;
	 Delayus(10);
     SCL_H;
	 Delayus(10);
     SCL_L;

     return I2Cdata;
}
unsigned char I2CReadNAK()
{
     unsigned char mask;
     unsigned char I2Cdata;

     SDA_H;
     SDA_in;

     for(mask = 0x80;mask != 0; mask >>= 1)
     {
		 Delayus(10);
          SCL_H;
          if(P16 == 0)
              I2Cdata &= ~mask;
          else
              I2Cdata |= mask;
		  Delayus(10);
          SCL_L;
     }
     SDA_out;
	 Delayus(5);
     SDA_H;
	 Delayus(10);
     SCL_H;
	 Delayus(10);
     SCL_L;

     return I2Cdata;
}



void read_ACK(void)    //等待 24C02 回应 ACK
{
	unsigned char t=0;
	SCL_H;
	Delayus(0);
	while((P16 ==1)&&(t<200))t++;	 //等待ACK，超时跳出
	SCL_L;
	Delayus(0);
}

void tmp_write_byte(unsigned char date)       //向24C02中写一个字节的数据
{
	unsigned char mask=0x80;
	SDA_out;
	SCL_L;
	for(mask=0x80;mask!=0;mask>>=1)    //从高位到低位依次进行
	{
		
		if((mask&date)==0)
		{
			SDA_L;
		}
		else
		{
			SDA_H;
		}
		Delayus(2);
		SCL_H;
		Delayus(2);
		SCL_L;
	}
	

}



